import mockConfig from './config/index';
import { sendSuccess, sendFail } from "./utils";
import { getList, addData, updateData, deleteData, batchDeleteData, findOne } from "./utils/readFile";

const prefix = `${mockConfig.prefix}/system`

export default [
  {
    url: `${prefix}/table/list`,
    timeout: mockConfig.timeout,
    method: "get",
    response: (ctx) => {
      const data = getList('system_table', ctx.query)
      return sendSuccess(data);
    },
  },
  {
    url: `${prefix}/table`,
    timeout: mockConfig.timeout,
    method: "post",
    response: (ctx) => {
      const target = findOne('system_table', ctx.body.tableValue, 'tableValue')
      if (target) {
        return sendFail({}, 'tableValue已存在');
      }
      const data = addData('system_table', ctx.body)
      return sendSuccess(data);
    },
  },
  {
    url: `${prefix}/table`,
    timeout: mockConfig.timeout,
    method: "put",
    response: (ctx) => {
      const target = findOne('system_table', ctx.body.tableValue, 'tableValue')
      if (target && target.id !== ctx.body.id) {
        return sendFail({}, 'tableValue已存在');
      }
      const data = updateData('system_table', ctx.body)
      return sendSuccess(data);
    },
  },
  {
    url: `${prefix}/table`,
    timeout: mockConfig.timeout,
    method: "delete",
    response: (ctx) => {
      const { id } = ctx.body
      if (!Array.isArray(id)) {
        const data = deleteData('system_table', id)
        return sendSuccess(data);
      } else {
        const data = batchDeleteData('system_table', id)
        return sendSuccess(data);
      }
    },
  },
  {
    url: `${prefix}/table/detail`,
    timeout: mockConfig.timeout,
    method: "get",
    response: (ctx) => {
      const [key] = Object.keys(ctx.query)
      const [value] = Object.values(ctx.query)
      const data = findOne('system_table', value, key)
      return sendSuccess(data);
    },
  },
];
